/**
 * Created by xinhuang on 15/4/18.
 */
(function () {
  'use strict';
  angular.module('directives.form', [])
    .directive('inputQuarter', inputQuaterDirective)
    .directive('inputQuarterGroup', inputQuarterGroupDirective);

  function inputQuarterGroupDirective() {
    return {
      restrict: 'E',
      scope: {
        startTime: '=',
        endTime: '=',
        currentTime: '=',
        startTitle: '=',
        endTitle: '=',
      },
      template: '<input-quarter current-time="currentTime"  ng-model="startTime"  title={{startTitle}}></input-quarter>' +
      '<input-quarter current-time="currentTime"  ng-model="endTime" boolean-style={{endTitle}} title={{endTitle}}></input-quarter>',
      link: postLink
    };

    function postLink(scope,ele) {
			ele[0].onmousewheel = function(){
				return false;
			};
      //如果没有给定指定的title,那么给定默认值
      if(!scope.startTitle){
        scope.startTitle = '开始时间';
      }
      if(!scope.endTitle){
        scope.endTitle = '结束时间';
      }
      /*
       * 当「input-quater」改变的时候会发送「_inputQuarterChanged」事件, 此时判断开始时间是否大于结束时间
       * 若大于则利用event对象获取发生改变的「input-quarter」的作用域scope,
       * 通过$setValidity设置「greater」错误
       * 若小于等于则向下广播「_resetGreater」事件,用以去除「greater」错误
       *
       * 同时将新的值赋给「startTime」和「endTime」
       * */
      scope.$on('_inputQuarterChanged', function (evt) {
        evt.stopPropagation();
        if (Number(scope.startTime) <= Number(scope.endTime)) {
          scope.$broadcast('_resetGreater');
        } else {
          evt.targetScope.ngModelCtrl.$setValidity('greater', false);
        }
      });
    }
  }

  function inputQuaterDirective() {
    return {
      restrict: 'E',
      template: htmlString,
      require: 'ngModel',
      scope: {
        ngModel: '=',
        title: '@',
        currentTime: '=',
        booleanStyle: '@'
      },
      link: postLink
    };

    function postLink(scope, element, attr, ctrl) {
      var currentTime;
      scope.titleStyle = {
        // color: 'black'
      };
      //如果给了booleanStyle值,并且值为true,那么将此时间段上的title给隐藏掉(只适用于交易对比分析)
      scope.booleanStyle ? scope.titleStyle.visibility = 'hidden' : scope.titleStyle.visibility = 'visible';
      if(scope.title === '时间段1:' || scope.title === '时间段2:'){
        scope.titleStyle.color = 'black';
      };

      //如果给定了当前时间 ps:一般用于当前季度减少
      if(scope.currentTime){
        currentTime = {
          year: scope.currentTime.getFullYear(),
          quarter: Math.ceil((scope.currentTime.getMonth() + 1) / 3)
        }
      }else {
        currentTime = new Date();
        currentTime = {
          year: currentTime.getFullYear(),
          quarter: Math.ceil((currentTime.getMonth() + 1) / 3)
        };
      }
      //季度选择框参数
      scope.quarters = [
        {title: '第一季度', code: 1},
        {title: '第二季度', code: 2},
        {title: '第三季度', code: 3},
        {title: '第四季度', code: 4}
      ];
      scope.ngModelCtrl = ctrl;

      //初始化input和select的ngModel值
      scope.selectedDate = {
        year: currentTime.year,
        quarter: currentTime.quarter
      };
      //若「ngModel」的「modelValue」发生改变, 则分别改变年份和季度的值
      scope.ngModelCtrl.$formatters.push(function (value) {
        if(!value || is.not.string(value)){
          return;
        }
        var len = value.length;
        if (is.not.undefined(value) && is.not.empty(value)) {
          scope.selectedDate = {
            year: Number(value.slice(0, len - 1)),
            quarter: Number(value.slice(-1))
          };
          scope.$emit('_inputQuarterChanged');
        }
        return value;
      });
      //当前季度
      var currenQuarter = Math.ceil((new Date().getMonth() + 1) / 3);
      //监听selectedDate对象变化，该监听用来验证 「为空」和「超过当前时间」错误
      scope.$watch('selectedDate', function (nVal) {
        var required = nVal.year > 1999;
        var current;
        if(nVal.year < new Date().getFullYear() || nVal.year<currentTime.year){
          current = true;
        }else if(nVal.year === currentTime.year && nVal.quarter <= currentTime.quarter){
          current = true;
        }else if(nVal.year === new Date().getFullYear() && nVal.quarter <= currenQuarter){
          current = true;
        }else {
          current = false;
        }
        // var current = nVal.year < new Date().getFullYear() || nVal.year < currentTime.year || nVal.year === currentTime.year && (nVal.quarter <= currentTime.quarter || nVal.quarter <= currenQuarter);
        scope.ngModelCtrl.$setValidity('required', required);
        scope.ngModelCtrl.$setValidity('current', current);
        if(is.not.null(nVal.year)){
          scope.ngModel = nVal.year.toString() + nVal.quarter;
        } else {
          scope.ngModel = '0' + nVal.quarter;
        }
        scope.$emit('formInvalid', scope.ngModelCtrl.$invalid);
      }, true);

      //监听「_resetGreater」事件,用以清除「greater」错误
      scope.$on('_resetGreater', function () {
        scope.ngModelCtrl.$setValidity('greater', true);
        scope.$emit('formInvalid', scope.ngModelCtrl.$invalid);
      });
    }
  }

  var htmlString =
    '<div class="lin-time">' +
    '<md-input-container ng-class="{\'md-input-invalid\': ngModelCtrl.$invalid}" flex>' +
    '<label ng-style="titleStyle">{{title}}</label>' +
    '<input type="number" ng-model="selectedDate.year">' +
    '<div ng-messages="ngModelCtrl.$error">' +
    '<div ng-message="required">请输入正确时间</div>' +
    '<div ng-message="current">选择的时间不应大于当前时间</div>' +
    '<div ng-message="greater">开始时间不能大于结束时间</div>' +
    '</div>' +
    '</md-input-container>' +
    '<div class="quarter">' +
    '<md-select ng-model="selectedDate.quarter" style="width:100%">' +
    '<md-option ng-value="quarter.code" ng-repeat="quarter in quarters">' +
    '{{quarter.title}}' +
    '</md-option>' +
    '</md-select>' +
    '</div>' +
    '</div>';
})();